package com.ktmall.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.ktmall.utils.RespMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

@RestController
@RequestMapping("/uni/oss")
public class  OSSController {
    private final static String accessKey;//OSS的用户名
    private final static String secretKey;//OSS密钥
    private final static String endpoint;//OSS对外服务的访问域名
    private final static String buket;//OSS中的一种概念，相当于文件夹

    static String configFile = "application.properties";
    //OSS的相关配置参数
    static {
        Properties param = new Properties();//配置文件路劲
        try {
            //加载配置文件到输入流中
            InputStream is = OSSController.class.getClassLoader().getResourceAsStream(configFile);
            //从输入流中读取属性列表
            param.load(is);
            //根据指定的获取对应的值
            accessKey = param.getProperty("oss.accessKey");
            secretKey = param.getProperty("oss.secretKey");
            endpoint = param.getProperty("oss.endpoint");
            buket = param.getProperty("oss.bucketName");
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/policy")
    public RespMsg policy(){
        Map<String,String> respMap = null;
        String host = "https://" + buket + "." + endpoint;//host的格式为bucketname.endpoint
        //这个前缀其实就是一个目录，即会在OSS的文件管理中创建这个目录，后续我们所有上传的文件都会被保存到这个目录中
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/";//用户上传文件时指定的前缀
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKey,secretKey);

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime*1000;
            Date expiration = new Date(expireEndTime);
            //PostObject请求最大可支持的文件大小为5GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY,dir);

            String postPolicy = ossClient.generatePostPolicy(expiration,policyConds);
            byte[] binaryDate = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryDate);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String,String>();
            respMap.put("ossAccessId",accessKey);
            respMap.put("ossPolicy",encodedPolicy);
            respMap.put("ossSignature",postSignature);
            respMap.put("ossKey",dir + new Date().getTime() + ".png");
            respMap.put("host",host);
            respMap.put("expire",String.valueOf(expireEndTime / 1000));
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            ossClient.shutdown();
        }
        return RespMsg.success("OSS服务端签名数据获取成功！",respMap);
    }
}
